package base.thread_JUC2.chapter01.demo003;

// 输出质数任务
public class PrimeGenerator extends Thread{

    @Override
    public void run() {
        long number = 1L;

        while (true){
            // 输出质数
            if (isPrime(number)) {
                System.out.printf("%d is prime\n", number);
            }

            // 判断当前线程是否被打断,打断就结束循环，退出程序
            if (isInterrupted()) {
                System.out.println("The Prime Generator has been Interrupted");
                return ;
            }
            number++;
        }
    }

    // 判断是否质数
    private boolean isPrime (long number) {
        if (number <=2) {
            return true;
        }

        // 从 3 开始检查是否属于质数
        for (int i = 2; i < number; i++) {
            if ((number % i) == 0) {
                return false;
            }
        }
        return true;
    }
}
